package dbinit;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.product.model.Product;
import core.product.model.ProductOwner;
import core.util.HibernateCoreUtil;

public class InitProductOwner 
{
	public static ProductOwner getProductOwnerByProduct(Product p)
	{
		ProductOwner po = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				Query q = session.createQuery("from ProductOwner po where po.product = :product").setEntity("product", p);

				if(q.list().size() > 0)
				{
					po = (ProductOwner) q.list().get(0);
				}
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return po ;
	}
	public static Long doinit(Long productId , Long ownerId)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		ProductOwner po = getProductOwnerByProduct(InitProduct.getProductByUuid(productId));
		if(po == null)
		{
			po = new ProductOwner();
		}
		po.setOwner(InitBasicProfile.getBasicProfileByUuid(ownerId));
		po.setProduct(InitProduct.getProductByUuid(productId));
		Long uuid = null ;
		
		try
		{
			transaction = session.beginTransaction();
		    session.saveOrUpdate(po);
		    uuid = po.getUuid();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return uuid ;
	}
}
